package com.ganbo.pattern.proxy.dynamicproxy.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Random;

//1.抽象主题
interface Moveable {
    void move();
}

//2.真实主题
class Car implements Moveable {

    public void move() {
        try {
            Thread.sleep(new Random().nextInt(1000));
            System.out.println("骑车行驶中...");
        } catch (InterruptedException e) {
        }
    }
}

//3.事务处理器
class TimeHandler implements InvocationHandler {

    private Object target;

    public TimeHandler(Object target) {
        this.target = target;
    }

    public Object getInstance(ClassLoader loader, Class<?>[] interfaces) {
        return Proxy.newProxyInstance(loader, interfaces, this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        long startTime = System.currentTimeMillis();
        System.out.println("汽车开始行驶…");
        Object invoke = method.invoke(target, args);
        long stopTime = System.currentTimeMillis();
        System.out.println("汽车结束行驶…汽车行驶时间：" + (stopTime - startTime) + "毫秒！");
        return invoke;
    }
}

//4.测试
public class Test {

    public static void main(String[] args) {
        Car car = new Car();
        TimeHandler timeHandler = new TimeHandler(car);
        Moveable carProxy = (Moveable) timeHandler.getInstance(Car.class.getClassLoader(), car.getClass().getInterfaces());
        carProxy.move();
    }

}
